package servlets;

import beans.Shenqing;
import beans.Employee;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.ShenqingService;
import beans.UseOrder;
import service.UseOrderService;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

// 新增导入 Vehicle 和 Drivers 相关的类和服务
import beans.Vehicle;
import service.VehicleService;
import beans.Drivers;
import service.DriversService;

@WebServlet("/ShenqingServlet")
public class ShenqingServlet extends HttpServlet {
    private ShenqingService shenqingService = new ShenqingService();
    private UseOrderService useOrderService = new UseOrderService();
    // 新增实例化 VehicleService 和 DriversService
    private VehicleService vehicleService = new VehicleService();
    private DriversService driversService = new DriversService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String action = req.getParameter("action");
        System.out.println("收到POST请求，action=" + action);

        // 如果是提交申请
        if ("submit".equals(action)) {
            handleSubmitApplication(req, resp);
            return;
        }
        // 如果是处理通过或驳回
         else if ("approve".equals(action)) {
             handleApprove(req, resp);
             return;
         } else if ("reject".equals(action)) {
             handleReject(req, resp);
             return;
         }

        // 原有的查询逻辑 (或其他POST请求处理)
        handleQuery(req, resp); // 如果POST请求不是 submit, approve, reject，则按查询处理
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String action = req.getParameter("action");
        String orderId = req.getParameter("orderId"); // 检查是否有 orderId 参数

        // 根据 action 参数调用不同的处理方法
        if ("approve".equals(action)) {
            handleApprove(req, resp);
        } else if ("reject".equals(action)) {
            handleReject(req, resp);
        } else if (orderId != null && !orderId.trim().isEmpty()) { // 如果有 orderId 但没有特定 action，则认为是查看详情
             handleViewDetail(req, resp, orderId);
        } else {
            // 否则，调用原有的查询逻辑（显示列表）
            handleQuery(req, resp);
        }
    }

    // 新增方法：处理查看申请详情的请求
    private void handleViewDetail(HttpServletRequest req, HttpServletResponse resp, String orderId) throws ServletException, IOException {
        try {
            // 获取申请信息
            Shenqing shenqing = shenqingService.getShenqingById(orderId);

            if (shenqing == null) {
                req.setAttribute("error", "未找到对应的申请信息");
                 req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
                return;
            }

            // 获取所有车辆和司机列表
            List<Vehicle> vehicleList = vehicleService.getAllVehicles();
            List<Drivers> driverList = driversService.getAllDrivers();

            // 将申请信息、车辆列表和司机列表放入 request 属性
            req.setAttribute("shenqing", shenqing);
            req.setAttribute("vehicleList", vehicleList);
            req.setAttribute("driverList", driverList);

            // 转发到 ShenqingDetail.jsp 页面
            req.getRequestDispatcher("/pirt/driversBig/ShenqingDetail.jsp").forward(req, resp);

        } catch (Exception e) {
            System.out.println("处理查看申请详情时出错: " + e.getMessage());
            e.printStackTrace();
            req.setAttribute("error", "系统错误：" + e.getMessage());
            req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
        }
    }

    private void handleSubmitApplication(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 首先检查用户是否已登录
            HttpSession session = req.getSession(false);
            if (session == null) {
                System.out.println("用户未登录，重定向到登录页面");
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
                return;
            }

            // 从session中获取当前登录的员工信息
            Employee employee = (Employee) session.getAttribute("user");
            String role = (String) session.getAttribute("role");
            String username = (String) session.getAttribute("username");

            if (employee == null || username == null) {
                System.out.println("Session中没有用户信息，重定向到登录页面");
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
                return;
            }

            System.out.println("当前登录用户: " + employee.getEmployeeName() + " (ID: " + employee.getEmployeeID() + ")");

            // 获取表单数据
            String vehicleType = req.getParameter("vehicleType");
            String useDate = req.getParameter("useDate");
            String useTime = req.getParameter("useTime");
            String returnDate = req.getParameter("returnDate");
            String returnTime = req.getParameter("returnTime");
            String destination = req.getParameter("destination");
            String reason = req.getParameter("reason");
            String passengers = req.getParameter("passengers");
            String remarks = req.getParameter("remarks");

            // 数据验证
            if (vehicleType == null || vehicleType.trim().isEmpty() ||
                    useDate == null || useDate.trim().isEmpty() ||
                    returnDate == null || returnDate.trim().isEmpty() ||
                    destination == null || destination.trim().isEmpty() ||
                    reason == null || reason.trim().isEmpty() ||
                    passengers == null || passengers.trim().isEmpty()) {

                System.out.println("表单数据验证失败：存在空字段");
                req.setAttribute("errorMessage", "请填写所有必填项");
                req.getRequestDispatcher("/shenqing.jsp").forward(req, resp);
                return;
            }

            // 创建申请对象
            Shenqing shenqing = new Shenqing();

            // 使用从session中获取的真实员工ID
            shenqing.setEmployeeId(employee.getEmployeeID());
            shenqing.setCarType(vehicleType);
            shenqing.setDestination(destination);
            shenqing.setUsageReason(reason);
            shenqing.setPassengers(passengers);
            shenqing.setRemarks(remarks != null ? remarks : "");

            System.out.println("创建申请对象 - 员工ID: " + employee.getEmployeeID() +
                    ", 车辆类型: " + vehicleType +
                    ", 目的地: " + destination);

            // 解析日期时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                String departureTimeStr = useDate + " " + (useTime != null ? useTime : "08:00") + ":00";
                String returnTimeStr = returnDate + " " + (returnTime != null ? returnTime : "18:00") + ":00";

                Date departureTime = dateFormat.parse(departureTimeStr);
                Date returnTimeDate = dateFormat.parse(returnTimeStr);

                shenqing.setDepartureTime(departureTime);
                shenqing.setReturnTime(returnTimeDate);

                System.out.println("解析时间成功 - 用车时间: " + departureTimeStr + ", 还车时间: " + returnTimeStr);

                // 验证时间逻辑
                if (returnTimeDate.before(departureTime)) {
                    req.setAttribute("errorMessage", "还车时间不能早于用车时间");
                    req.getRequestDispatcher("/shenqing.jsp").forward(req, resp);
                    return;
                }

            } catch (ParseException e) {
                System.out.println("日期时间解析失败: " + e.getMessage());
                req.setAttribute("errorMessage", "日期时间格式错误");
                req.getRequestDispatcher("/shenqing.jsp").forward(req, resp);
                return;
            }

            // 提交申请
            System.out.println("准备提交申请到数据库...");
            int orderId = shenqingService.submitShenqing(shenqing);
            System.out.println("申请提交成功，生成订单号: " + orderId);

            // 重定向到成功页面，带上订单号
            resp.sendRedirect(req.getContextPath() + "/shenqing.jsp?success=true&orderId=" + orderId);

        } catch (SQLException e) {
            System.out.println("数据库操作失败: " + e.getMessage());
            e.printStackTrace();
            req.setAttribute("errorMessage", "系统错误，申请提交失败，请稍后重试");
            req.getRequestDispatcher("/shenqing.jsp").forward(req, resp);
        } catch (Exception e) {
            System.out.println("处理申请提交时发生未知错误: " + e.getMessage());
            e.printStackTrace();
            req.setAttribute("errorMessage", "系统错误，请稍后重试");
            req.getRequestDispatcher("/shenqing.jsp").forward(req, resp);
        }
    }

    private void handleQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        System.out.println("收到查询请求，action=" + action);

        try {
            List<Shenqing> shenqingList = null;

            if ("search".equals(action)) {
                String orderId = req.getParameter("orderId");
                System.out.println("搜索订单号: " + orderId);
                shenqingList = shenqingService.searchByOrderId(orderId);
            } else if ("all".equals(action)) {
                System.out.println("获取所有待审核申请");
                shenqingList = shenqingService.getPendingShenqing();
            } else if ("list".equals(action)) {
                System.out.println("获取已处理申请");
                shenqingList = shenqingService.getProcessedShenqing();
            } else {
                System.out.println("未知操作: " + action);
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "请求的操作不存在");
                return;
            }

            System.out.println("查询结果数量: " + (shenqingList != null ? shenqingList.size() : 0));
            req.setAttribute("shenqingList", shenqingList);
            req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);

        } catch (Exception e) {
            System.out.println("处理查询请求时出错: " + e.getMessage());
            e.printStackTrace();
            req.setAttribute("error", "系统错误：" + e.getMessage());
            req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
        }
    }

    private void handleApprove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取订单ID
            String orderIdStr = req.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.trim().isEmpty()) {
                req.setAttribute("error", "订单ID不能为空");
                req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
                return;
            }
             int orderId = Integer.parseInt(orderIdStr);

            // 获取选择的车辆和司机ID
            String vehicleIdStr = req.getParameter("vehicleId");
            String driverIdStr = req.getParameter("driverId");

            if (vehicleIdStr == null || vehicleIdStr.trim().isEmpty() || driverIdStr == null || driverIdStr.trim().isEmpty()) {
                 req.setAttribute("error", "请选择车辆和司机");
                 // 这里可能需要转发回 ShenqingDetail.jsp 并显示错误信息
                 req.getRequestDispatcher("/pirt/driversBig/ShenqingDetail.jsp?orderId=" + orderId).forward(req, resp);
                 return;
            }
             int vehicleId = Integer.parseInt(vehicleIdStr);
             int driverId = Integer.parseInt(driverIdStr);


            // 获取申请信息
            Shenqing shenqing = shenqingService.getShenqingById(orderIdStr); // getShenqingById 接收 String
            if (shenqing == null) {
                req.setAttribute("error", "未找到对应的申请信息");
                req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
                return;
            }

             // 获取当前登录用户（审核人）
            HttpSession session = req.getSession(false);
            if (session == null || session.getAttribute("user") == null) {
                resp.sendRedirect(req.getContextPath() + "/login.jsp"); // 用户未登录，重定向到登录页面
                return;
            }
            Employee reviewerEmployee = (Employee) session.getAttribute("user");
            Integer reviewerId = reviewerEmployee.getEmployeeID(); // 获取审核人ID


            // 更新申请状态为"已通过"
            shenqing.setStatus("已通过");
            shenqingService.updateShenqingStatus(shenqing); // 确保 updateShenqingStatus 能够处理 Shenqing 对象

            // 创建 UseOrder 对象并填充数据
            UseOrder approvedOrder = new UseOrder();
            approvedOrder.setOrderId(String.valueOf(shenqing.getOrderId())); // orderId 在 UseOrder 是 String
            approvedOrder.setEmployeeId(shenqing.getEmployeeId());
            approvedOrder.setDriverId(driverId); // 设置分配的司机ID
            approvedOrder.setExpectedDepartureTime(shenqing.getDepartureTime());
            approvedOrder.setExpectedReturnTime(shenqing.getReturnTime());
            approvedOrder.setRemarks(shenqing.getRemarks());
            approvedOrder.setVehicleId(vehicleId); // 设置分配的车辆ID
            approvedOrder.setUsageReason(shenqing.getUsageReason());
            approvedOrder.setPassengers(shenqing.getPassengers());
            approvedOrder.setReviewStatus("已通过"); // 设置状态为"已通过"
            approvedOrder.setReviewer(reviewerId); // 设置审核人ID
            approvedOrder.setPurpose(""); // 根据需要设置默认值或从 Shenqing 获取
            approvedOrder.setDestination(shenqing.getDestination());
            approvedOrder.setStatusremarks("申请已通过"); // 状态备注

            // 将数据插入 use_order 表
            boolean inserted = useOrderService.addUseOrder(approvedOrder);
            if (!inserted) {
                System.out.println("插入 use_order 表失败，订单号: " + orderId);
                // 可以选择记录错误或给用户提示
            } else {
                 System.out.println("插入 use_order 表成功，订单号: " + orderId);
            }


            // 重定向回任务列表页面
            resp.sendRedirect(req.getContextPath() + "/ShenqingServlet?action=all");
        } catch (NumberFormatException e) {
             System.out.println("订单ID、车辆ID或司机ID格式错误: " + e.getMessage());
             e.printStackTrace();
             req.setAttribute("error", "订单ID、车辆ID或司机ID格式错误");
             req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
        }
        catch (Exception e) {
            System.out.println("处理通过申请时出错: " + e.getMessage());
            e.printStackTrace();
            req.setAttribute("error", "系统错误：" + e.getMessage());
            req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
        }
    }

    private void handleReject(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String orderId = req.getParameter("orderId");
        System.out.println("收到驳回请求，订单ID: " + orderId); // 添加日志确认收到请求和ID

        if (orderId == null || orderId.trim().isEmpty()) {
            System.out.println("订单ID为空"); // 日志
            req.setAttribute("error", "订单ID不能为空");
            req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp); // 转发到列表页显示错误
            return;
        }

        try {
            // 获取申请信息
            Shenqing shenqing = shenqingService.getShenqingById(orderId);
            if (shenqing == null) {
                System.out.println("未找到订单ID为 " + orderId + " 的申请信息"); // 日志
                req.setAttribute("error", "未找到对应的申请信息");
                req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp); // 转发到列表页显示错误
                return;
            }

            // 检查用户是否登录（虽然理论上审核人页面已检查，但这里再加一层保障）
            HttpSession session = req.getSession(false);
            if (session == null || session.getAttribute("user") == null) {
                 System.out.println("用户未登录，重定向到登录页面"); // 日志
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
                return;
            }
            // Employee reviewerEmployee = (Employee) session.getAttribute("user"); // 审核人ID通过触发器处理，这里不需要获取

            // 之前的 use_order 插入逻辑已移除，依赖触发器

            // 更新申请状态为"未通过"
            shenqing.setStatus("未通过");
            shenqingService.updateShenqingStatus(shenqing); // 调用Service更新状态
            System.out.println("申请状态更新为未通过，订单号: " + orderId); // 日志确认Service调用成功

            // 重定向回任务列表页面
            System.out.println("驳回成功，重定向到待办任务列表"); // 日志
            resp.sendRedirect(req.getContextPath() + "/ShenqingServlet?action=all");

        } catch (Exception e) {
            // 捕获其他潜在异常
            System.out.println("处理驳回申请时发生未知错误: " + e.getMessage());
            e.printStackTrace(); // 打印详细堆栈跟踪
            req.setAttribute("error", "系统错误，驳回申请失败，请稍后重试");
            req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
        }
    }
}
